package com.lnj.orders.controller;

import com.lnj.bean.dto.OrdersDTO;
import com.lnj.bean.dto.OrdersItemsDTO;
import com.lnj.orders.service.OrdersService;
import com.lnj.orders.utils.*;
import com.lnj.utils.OrderMessage;
import com.lnj.utils.ResponseResult;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @program: shopping147_cloud
 * @description:
 * @author: zy
 * @create: 2025-08-01 16:03
 */
@RestController
@RequestMapping("/orders/operation")
@AllArgsConstructor
public class OrdersController {
    @Autowired
    private final OrdersService ordersService;
    @Autowired
    private final Executor executor;
    @Autowired
    private final AliPayUtil aliPayUtil;
    @Autowired
    private final KafkaTemplate kafkaTemplate;
    @Autowired
    private JsonUtil jsonUtil;

    @PostMapping("/create")
    public ResponseEntity<ResponseResult> createOrder(
            @RequestHeader("X-User-ID") Long userId,
            @RequestBody OrderCreateRequest request) { // 接收新的请求体对象
        try {
            OrdersDTO order = ordersService.createOrder(userId, request.getOrdersDTO(), request.getOrderItemsDTOList(), request.getCartIds());
            List<OrdersItemsDTO> orderItemsDTOList = request.getOrderItemsDTOList();
            //利用原子类
            AtomicReference<Double> totalPrice= new AtomicReference<>(0.0D);
            if (orderItemsDTOList!=null && !orderItemsDTOList.isEmpty()){
                orderItemsDTOList.forEach(orderItemsDTO -> {
                    totalPrice.updateAndGet(v -> v + orderItemsDTO.getPrice() * orderItemsDTO.getQuantity());
                });
            }
            order.setTotalPrice(totalPrice.get());
            executor.execute(() -> {
                aliPayUtil.generateQRCodePay(order.getId().toString(), totalPrice.get().toString());
            });

            //把订单创建成功的消息发送到kafka
            OrderMessage message = new OrderMessage();
            message.setOrderId(order.getId());
            message.setCreateTime(LocalDateTime.now());
            message.setEventType("created");
            message.setRemindCount(0);
            message.setCurrentStatus(1);
            String messageJson = jsonUtil.toJson(message);
            kafkaTemplate.send("orders.created", messageJson);

            return new ResponseEntity<>(ResponseResult.ok("订单创建成功").setData(order), HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(ResponseResult.error("订单创建失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    //根据订单ID查询订单信息
    @GetMapping("/get")
    public ResponseEntity<ResponseResult> getOrder(@RequestParam("orderId") Long orderId
                                                    ,@RequestParam("orderStatus") Long orderStatus) {
        try {
            OrdersDTO order = ordersService.getOrderById(orderId,orderStatus);
            if (order == null) {
                return new ResponseEntity<>(ResponseResult.error("订单不存在"), HttpStatus.NOT_FOUND);
            }
            Double totalPrice = ordersService.calculateTotalPrice(orderId);
            order.setTotalPrice(totalPrice);
            return new ResponseEntity<>(ResponseResult.ok("订单获取成功").setData(order), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(ResponseResult.error("订单获取失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    //根据订单ID获取订单详情
    @GetMapping("/detail/{orderId}")
    public ResponseEntity<ResponseResult> getOrderDetail(@PathVariable Long orderId) {
        try {
            List<ProductOrderInfo> order = ordersService.getOrderdetalById(orderId);
            if (order == null) {
                return new ResponseEntity<>(ResponseResult.error("订单不存在"), HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<>(ResponseResult.ok("订单详情获取成功").setData(order), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(ResponseResult.error("订单详情获取失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    //根据订单ID取消订单
    @PostMapping("/cancel/{orderId}")
    public ResponseEntity<ResponseResult> getOrderStatus(@PathVariable Long orderId) {
        try {
            Integer status = ordersService.cancelOrder(orderId);
            if (status == 0) {
                return new ResponseEntity<>(ResponseResult.error("订单不存在"), HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<>(ResponseResult.ok("订单取消成功").setData(status), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(ResponseResult.error("订单状态获取失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    //根据订单状态查询订单列表
    @GetMapping("/list")
    public ResponseEntity<ResponseResult> getOrderList(@RequestHeader("X-User-ID") Long userId,
                                                       @RequestParam("ordersStatus") Long ordersStatus) {
        try {
            List<OrderListResponse> orders = ordersService.getOrderList(userId,ordersStatus);
            if (orders == null) {
                return new ResponseEntity<>(ResponseResult.error("订单不存在"),  HttpStatus.OK);
            }
            return new ResponseEntity<>(ResponseResult.ok("订单列表获取成功").setData(orders), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(ResponseResult.error("订单列表获取失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
